const db = require("../models/index");
const { Op, where } = require("sequelize");
const user = require("../models/user");
const { regionTime } = require("../utils/regionTime");
const User = db.user;
const Project = db.project;
const Need = db.need;
const Bug = db.bug;
const UserProject = db.user_project;
const UserBug = db.user_bug;
const UserNeed = db.user_need;
const History = db.needHistory;

// // 发布需求1.0
// exports.needPublish = async (req, res) => {
//   // 需求基本信息
//   const {
//     projectId,
//     projectName,
//     title,
//     details,
//     priority,
//     startDate,
//     endDate,
//     category,
//   } = req.body;

//   // 需求处理人数组
//   const handlers = req.body.handlers;

//   // 获取用户信息作为需求创建人
//   const realName = req.user.realName;
//   const userId = req.user.id;

//   if (!title) {
//     return res.status(400).json({ code: 400, errorMsg: "标题不能为空" });
//   }

//   // 检查日期字段，如果是空字符串，则设置为null
//   const formattedStartDate = startDate || null;
//   const formattedEndDate = endDate || null;

//   try {
//     // 检查 projectId 是否存在
//     const project = await Project.findOne({ where: { id: projectId } });
//     if (!project) {
//       return res.status(404).json({ code: 400, errorMsg: "项目不存在" });
//     }

//     const newNeed = await Need.create({
//       creator: realName,
//       creatorId: userId,
//       projectId,
//       projectName,
//       title,
//       details,
//       priority,
//       category,
//       priority,
//       startDate: formattedStartDate,
//       endDate: formattedEndDate,
//     });

//     // 建立需求与处理人之间的关联
//     await newNeed.setHandler(handlers);

//     res.status(201).json({
//       code: 201,
//       msg: "需求创建成功",
//       data: newNeed,
//     });
//   } catch (error) {
//     console.error(error);
//     res.status(500).json({ code: 500, errorMsg: error.message });
//   }
// };

// 发布需求2.0
exports.needPublish = async (req, res) => {
  // 需求基本信息
  const {
    projectId,
    title,
    details,
    priority,
    startDate,
    endDate,
    category,
    handlerArray,
  } = req.body;

  // // 需求处理人数组
  const handlerArrayJson = JSON.stringify(handlerArray);
  // 获取用户信息作为需求创建人、变更人
  const realName = req.user.realName;
  const userId = req.user.id;

  if (!title) {
    return res.status(400).json({ code: 400, errorMsg: "标题不能为空" });
  }

  // 检查日期字段，如果是空字符串，则设置为null
  const formattedStartDate = startDate || null;
  const formattedEndDate = endDate || null;

  try {
    // 检查 projectId 是否存在
    const project = await Project.findOne({ where: { id: projectId } });
    if (!project) {
      return res.status(404).json({ code: 400, errorMsg: "项目不存在" });
    }

    const newNeed = await Need.create({
      creator: realName,
      creatorId: userId,
      projectId,
      projectName: project.projectName,
      title,
      details,
      priority,
      category,
      priority,
      handlerArray: handlerArrayJson,
      startDate: formattedStartDate,
      endDate: formattedEndDate,
      changerName: realName,
      changerId: userId,
      changeType: "新增",
    });

    if (handlerArray) {
      // 需求处理人数组
      const handlersId = handlerArray.map((handler) => {
        return handler.id;
      });

      // 建立需求与处理人之间的关联
      await newNeed.setHandler(handlersId);
    }

    res.status(201).json({
      code: 201,
      msg: "需求创建成功",
      data: { needId: newNeed.id },
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 所在项目的需求列表
exports.getProjectNeeds = async (req, res) => {
  const projectId = req.params.projectId;

  try {
    // 查询项目是否存在
    const project = await Project.findOne({ where: { id: projectId } });
    if (!project) {
      return res.status(404).json({ code: 404, errorMsg: "项目不存在" });
    }

    // 查询该项目下的所有需求
    const needs = await Need.findAll({
      where: { projectId },
      attributes: [
        "id",
        "title",
        "details",
        "creator",
        "createdAt",
        "priority",
        "category",
        "startDate",
        "endDate",
        "status",
        "handlerArray",
      ],
    });
    // 需求处理人数组JSON转化
    needs.forEach((need) => {
      need.handlerArray = JSON.parse(need.handlerArray);
      // // 时区转换  2024年5月9日
      need.setDataValue("createdAt", regionTime(need.createdAt));
      need.setDataValue("startDate", regionTime(need.startDate));
      need.setDataValue("endDate", regionTime(need.endDate));
    });

    res.status(200).json({
      code: 200,
      msg: "需求列表获取成功",
      data: needs,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 查看需求详情
exports.getNeedDetail = async (req, res) => {
  const needId = req.params.needId;

  try {
    const need = await Need.findOne({
      where: { id: needId },
      attributes: [
        "id",
        "title",
        "details",
        "createdAt",
        "priority",
        "category",
        "startDate",
        "endDate",
        "status",
        "creator",
        "handlerArray",
      ],
    });
    if (!need) {
      return res.status(404).json({ code: 404, msg: "需求不存在" });
    }
    need.handlerArray = JSON.parse(need.handlerArray);
    // // 获取需求的处理人
    // const handlersId = await UserNeed.findAll({
    //   where: { needId },
    //   attributes: ["userId"],
    // });

    // const handlers = [];
    // for (let i = 0; i < handlersId.length; i++) {
    //   const handler = await User.findOne({
    //     where: { id: handlersId[i].userId },
    //     attributes: ["realName"],
    //   });
    //   handlers.push(handler.realName);
    // }

    // 时区转换 2024年5月9日
    // console.log(need.createdAt);   (-.-)~zzZ
    //错误方案|| need.createdAt = regionTime(need.createdAt);||ヽ(ー_ー)ノ??因为need为实例，不能直接赋值createdAt，需要用setDataValue方法
    need.setDataValue("createdAt", regionTime(need.createdAt));
    need.setDataValue("startDate", regionTime(need.startDate));
    need.setDataValue("endDate", regionTime(need.endDate));
    // console.log(need.createdAt);

    // 需求评论区列表
    const comments = await History.findAll({
      where: {
        needId,
        comment: {
          [Op.ne]: null,
        },
      },
      attributes: ["id", "comment", "changerName", "updatedAt"],
      order: [["id", "DESC"]],
    });

    res.status(200).json({
      code: 200,
      msg: "需求详情获取成功",
      data: need,
      comments,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: error.message });
  }
};

// 已废弃，已合并// 需求评论区列表
// exports.getNeedComment = async (req, res) => {
//   const needId = req.params.needId;

//   try {
//     const comments = await History.findAll({
//       where: {
//         needId,
//         comment: {
//           [Op.ne]: null,
//         },
//       },
//       attributes: ["id", "comment", "changerName", "updatedAt"],
//       order: [["id", "DESC"]],
//     });

//     res.status(200).json({ message: "评论列表获取成功", comments });
//   } catch (error) {
//     console.error(error);
//     res.status(500).json({ error: error.message });
//   }
// };

// 流转需求\更改需求
exports.rollNeed = async (req, res) => {
  const changerId = req.user.id;
  const changerName = req.user.realName;
  const {
    needId,
    priority,
    startDate,
    endDate,
    status,
    comment,
    handlerArray,
  } = req.body;
  try {
    // 查询需求是否存在
    const need = await Need.findOne({
      where: { id: needId },
    });
    if (!need) {
      return res.status(404).json({ code: 404, errorMsg: "需求不存在" });
    }
    // 重新建立需求与处理人之间的关联
    if (handlerArray) {
      const handlersId = handlerArray.map((handler) => {
        return handler.id;
      });
      await need.setHandler(handlersId);
    }
    // 变更需求
    const updatedNeed = await need.update({
      priority,
      startDate,
      endDate,
      comment,
      status,
      changerId,
      changerName,
      handlerArray: JSON.stringify(handlerArray),
      changeType: "流转",
    });
    console.log(updatedNeed.get({ plain: true }));
    //0.2废案/ 记录变更人
    // const latestHistory = await History.findOne({
    //   where: { needId: needId },
    //   order: [["id", "DESC"]], // 按id倒序排列，取最新一条记录
    // });
    // if (latestHistory) {
    //   const updatedHistory = await latestHistory.update({
    //     changerId: userId,
    //     changerName: realName,
    //   });
    //   console.log(updatedHistory);
    // }

    // const {parentId, projectName,...needInfo} = updatedNeed;
    res.status(200).json({ code: 200, msg: "需求已流转" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 获取需求历史
exports.getNeedHistory = async (req, res) => {
  const needId = req.params.needId;

  try {
    // historys变更基本信息
    const historys = await History.findAll({
      where: {
        needId,
      },
      attributes: [
        "id",
        "changedField",
        "updatedAt",
        "changerName",
        "changeType",
      ],
      // order: [["id", "DESC"]],
    });

    //afterUpdate变更后的值;beforeUpdate变更前的值
    let afterUpdate = [];
    let beforeUpdate = [];
    for (let i = 0; i < historys.length; i++) {
      // 把实例转换成对象
      historys[i] = historys[i].get({ plain: true });
      // console.log(historys[i]);
      historys[i].changedField = JSON.parse(historys[i].changedField);
      // console.log(historys[i].changedField);

      //  时区转换  2024年5月9日
      historys[i].updatedAt = regionTime(historys[i].updatedAt);

      afterUpdate[i] = (
        await History.findOne({
          where: {
            needId,
            id: historys[i].id,
          },
          attributes: historys[i].changedField,
        })
      ).dataValues;
      // 需求处理人数组JSON转化
      if (afterUpdate[i].handlerArray) {
        afterUpdate[i].handlerArray = JSON.parse(afterUpdate[i].handlerArray);
      }
      // 时区转换 2024年5月9日
      if (afterUpdate[i].startDate) {
        afterUpdate[i].startDate = regionTime(afterUpdate[i].startDate);
      }
      if (afterUpdate[i].endDate) {
        afterUpdate[i].endDate = regionTime(afterUpdate[i].endDate);
      }

      // 单独处理，后续将beforeUpdate数组中第一个对象的所有属性值设为"--"
      if (i === 0) {
        beforeUpdate[i] = (
          await History.findOne({
            where: {
              needId,
              id: historys[i].id,
            },
            attributes: historys[i].changedField,
          })
        ).get({ plain: true });

        // 删掉实际没有更改的字段
        if (afterUpdate[i].startDate === null) {
          delete afterUpdate[i].startDate;
        }
        if (afterUpdate[i].endDate === null) {
          delete afterUpdate[i].endDate;
        }
      } else {
        beforeUpdate[i] = (
          await History.findOne({
            where: {
              needId,
              id: historys[i - 1].id,
            },
            attributes: historys[i].changedField,
          })
        ).get({ plain: true });
      }

      // 映射对象存储字段名和对应的中文翻译
      const fieldTranslations = {
        title: "标题",
        details: "详情",
        priority: "优先级",
        category: "分类",
        startDate: "开始日期",
        endDate: "截止日期",
        status: "状态",
        handlerArray: "处理人",
        comment: "评论",
        creator: "创建人",
      };

      // 将字段名转换为中文
      for (let j = 0; j < historys[i].changedField.length; j++) {
        const originalField = historys[i].changedField[j];
        if (fieldTranslations[originalField]) {
          historys[i].changedField[j] = fieldTranslations[originalField];
        }
      }

      // 需求处理人数组JSON转化
      if (beforeUpdate[i].handlerArray) {
        beforeUpdate[i].handlerArray = JSON.parse(beforeUpdate[i].handlerArray);
      }
      // 时区转换 2024年5月9日
      if (beforeUpdate[i].startDate) {
        beforeUpdate[i].startDate = regionTime(beforeUpdate[i].startDate);
      }
      if (beforeUpdate[i].endDate) {
        beforeUpdate[i].endDate = regionTime(beforeUpdate[i].endDate);
      }
    }

    // 将beforeUpdate数组中第一个对象的所有属性值设为"--"
    (function (arr) {
      if (arr.length > 0) {
        const firstObj = arr[0];
        for (let key in firstObj) {
          firstObj[key] = "--";
        }
      }
    })(beforeUpdate);

    // 将属性值为null的字段设为"--"
    const handleNullFields = function (Array) {
      if (Array.length > 0) {
        for (let i = 1; i < beforeUpdate.length; i++) {
          const arr = Array[i];
          for (let key in arr) {
            if (!arr[key]) {
              arr[key] = "--";
            }
          }
        }
      }
    };
    handleNullFields(beforeUpdate);
    handleNullFields(afterUpdate);

    res.status(200).json({ historys, beforeUpdate, afterUpdate });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: error.message });
  }
};

// 修改自己创建的需求标题、详情、优先级、分类、开始日期、截止日期、状态、处理人
exports.modifyNeed = async (req, res) => {
  const needId = req.params.needId;
  const {
    title,
    details,
    priority,
    category,
    startDate,
    endDate,
    status,
    handlerArray,
  } = req.body;

  try {
    // 查询需求是否存在
    const need = await Need.findOne({
      where: { id: needId },
    });
    if (!need) {
      return res.status(404).json({ code: 404, errorMsg: "需求不存在" });
    }

    // 重新建立需求与处理人之间的关联
    if (handlerArray) {
      const handlersId = handlerArray.map((handler) => {
        return handler.id;
      });
      await need.setHandler(handlersId);
    }

    // 更新需求
    const updatedNeed = await need.update({
      title,
      details,
      priority,
      category,
      startDate,
      endDate,
      status,
      handlerArray: JSON.stringify(handlerArray),
      changerId: req.user.id,
      changerName: req.user.realName,
      changeType: "修改",
    });

    console.log(updatedNeed);

    res.status(200).json({
      code: 200,
      msg: "需求已修改",
      data: { needId: needId },
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 删除需求
exports.deleteNeed = async (req, res) => {
  const needId = req.params.needId;

  try {
    // 查询需求是否存在
    const need = await Need.findOne({
      where: { id: needId },
    });
    if (!need) {
      return res.status(404).json({ code: 404, errorMsg: "需求不存在" });
    }
    console.log("____");
    // console.log(...need.dataValues);

    // 记录需求变更历史
    await need.update({
      status: "已删除",
      changerId: req.user.id,
      changerName: req.user.realName,
      changeType: "删除",
    });
    // const historys = await History.create({
    //   needId,
    //   changerId: req.user.id,
    //   changerName: req.user.realName,
    //   changeType: "删除",
    // });

    // 删除需求
    await need.destroy();

    res
      .status(200)
      .json({ code: 200, msg: "需求已删除", data: { needId: needId } });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 恢复需求
exports.restoreNeed = async (req, res) => {
  const needId = req.params.needId;

  try {
    console.log(Need.options.paranoid);
    // 查询需求是否存在
    // const need = await Need.findOne({
    //   where: { id: needId },
    //   paranoid: false,
    // });
    const need = await Need.findByPk(needId, { paranoid: false });
    if (!need) {
      return res.status(404).json({ code: 404, errorMsg: "需求不存在" });
    }

    // 恢复需求
    // await need.restore();
    await need.restore({ paranoid: true });

    // 记录需求变更历史
    const needRestored = await need.update({
      status: "规划中",
      changerId: req.user.id,
      changerName: req.user.realName,
      changeType: "恢复",
    });
    // console.log(needRestored.get({ plain: true }));

    // const historys = await History.create({
    //   needId,
    //   changerId: req.user.id,
    //   changerName: req.user.realName,
    //   changeType: "恢复",
    // });

    res
      .status(200)
      .json({ code: 200, msg: "需求已恢复", data: { needId: needId } });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};
